#!/usr/bin/perl
#
use 5.010;
use strict;

my $numEntries = shift @ARGV;
my $type = shift @ARGV;

my @files = glob "wdbc*";

my %fileScore = ();

sub fileScore {
    my $fileName = shift;
    my $score;

    open my $file, '<', $fileName; 

    
    for my $line (<$file>) {
        if ($line =~ /Error medio: (.*)$/) {
            $score = 0 + $1;
        }
    }

    return $score;
}

for my $filename (@files) {
    my $score = fileScore( $filename );
    $fileScore{$filename} = $score;
}


if ($type eq "best") {
    my @sortedFiles = sort { $fileScore{$a} <=> $fileScore{$b} } keys(%fileScore);
    say "$_ SCORE $fileScore{$_}" foreach @sortedFiles[0 .. $numEntries-  1];
} elsif ($type eq "worst") {
    my @sortedFiles = sort { $fileScore{$b} <=> $fileScore{$a} } keys(%fileScore);
    say "$_ SCORE $fileScore{$_}" foreach @sortedFiles[0 .. $numEntries - 1];
} else {
    say "Argumento $type invalido";
    say "Uso del programa: ./bestest.pl <numEntradas> [best|worst]";
}

